<template>
	<view class="wallet-page">
		<!-- 顶部导航栏 -->
		<u-navbar :placeholder="true" :safeAreaInsetTop="true" :height="44" bg-color="#ff5722" title="我的钱包"
			title-color="#fff" :left-icon-size="20" left-icon-color="#fff" @leftClick="goBack">
			<template #right>
				<view class="nav-right" @click="goBill">
					<text class="bill-text">账单</text>
				</view>
			</template>
		</u-navbar>

		<!-- 钱包背景卡片 -->
		<view class="wallet-bg">
			<image class="wallet-bg-image" :src="serverAddress + 'img/mingbag.png'"></image>
			<text class="balance-amount">¥{{ walletInfo.money || '0.00' }}</text>
			<text class="balance-label">总资产</text>
		</view>

		<!-- 功能列表 -->
		<view class="function-list">
			<!-- 待分润 -->
			<view class="function-item" @click="handleWithdraw">
				<view class="item-left">
					<image class="item-icon" :src="serverAddress+'img/icon-dfr@3x.png'"></image>
					<text class="item-title">待分润</text>
				</view>
				<view class="item-right">
					<text class="frozen-money">¥{{ walletInfo.frozen_money || '0.00' }}</text>
				</view>
			</view>

			<!-- 账户余额 -->
			<view class="function-item" @click="handleWithdraw">
				<view class="item-left">
					<image class="item-icon" :src="serverAddress+'img/pay1.jpg'"></image>
					<text class="item-title">账户余额</text>
				</view>
				<view class="item-right">
					<text class="withdraw-money">¥{{ walletInfo.withdraw_money || '0.00' }}</text>
					<image class="arrow-right" :src="serverAddress+'img/right1.png'"></image>
				</view>
			</view>


		</view>
		<!-- 银行卡 -->
		<view class="function-item margin-top" @click="goBankCard">
			<view class="item-left">
				<image class="item-icon" :src="serverAddress+'img/icon-Bank-card@3x.png'"></image>
				<text class="item-title">银行卡</text>
			</view>
			<view class="item-right">
				<image class="arrow-right" :src="serverAddress+'img/right1.png'"></image>
			</view>
		</view>
		<!-- 底部提示 -->
		<view class="bottom-tip">
			<text class="tip-text">本服务由优享优品提供</text>
			<text class="tip-link" @click="goFAQ">常见问题</text>
		</view>

		<!-- 支付宝账号输入弹窗 -->
		<view v-if="showAlipayModal" class="modal-mask" @click="hideAlipayModal">
			<view class="alipay-modal" @click.stop>
				<view class="modal-title">请输入支付宝账号</view>
				<view class="input-wrapper">
					<input v-model="alipayAccount" type="text" placeholder="请输入支付宝账号(必填)" :focus="showAlipayModal" />
				</view>
				<view class="modal-buttons">
					<view class="btn-cancel" @click="hideAlipayModal">取消</view>
					<view class="btn-confirm" @click="confirmAlipayAccount">确定</view>
				</view>
			</view>
		</view>

		<!-- 提现方式选择弹窗 -->
		<view v-if="showCashTypeModal" class="modal-mask" @click="hideCashTypeModal">
			<view class="cash-type-modal" @click.stop>
				<view class="modal-header">请选择提现方式？</view>
				<view class="modal-desc">每日最多提现1笔，每笔100-5000元，每日最高5000元</view>
				<view class="cash-option" @click="selectBankCard">提现到银行卡</view>
				<view class="cash-option" @click="selectAlipay">提现到支付宝</view>
			</view>
		</view>

		<!-- 提现金额输入弹窗 -->
		<view v-if="showCashAmountModal" class="modal-mask" @click="hideCashAmountModal">
			<view class="cash-amount-modal" @click.stop>
				<view class="modal-title">请输入提现金额</view>
				<view class="modal-desc">支付宝每笔仅支持100-50000元，每日最多两笔最多50000</view>
				<view class="amount-input-wrapper">
					<input v-model="cashAmount" type="number" placeholder="请输入金额" :focus="showCashAmountModal" />
				</view>
				<view class="modal-buttons">
					<view class="btn-cancel" @click="hideCashAmountModal">取消</view>
					<view class="btn-confirm" @click="submitCashAmount">确定</view>
				</view>
			</view>
		</view>

		<!-- 支付密码验证弹窗 -->
		<view v-if="showPayPasswordModal" class="modal-mask">
			<view class="pay-password-modal" @click.stop>
				<view class="modal-header">
					<image class="back-btn" :src="serverAddress+'img/icon-Get-into@3.png'"
						@click="hidePayPasswordModal"></image>
					<text class="modal-title">{{ payPasswordTitle }}</text>
				</view>
				<view class="password-content">
					<view class="password-tip">请输入支付密码</view>
					<view class="password-input-wrapper">
						<input v-model="payPassword" type="password" maxlength="6" :focus="showPayPasswordModal"
							@input="handlePasswordInput" />
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		walletApi,
		identityApi
	} from '@/api/index.js'
	import {
		md5
	} from '@/utils/md5.js'
	import {
		inject
	} from 'vue'

	export default {
		data() {
			return {
				serverAddress: inject('$serverAddress', ''),
				// 钱包信息
				walletInfo: {
					money: '0.00',
					frozen_money: '0.00',
					withdraw_money: '0.00'
				},

				// 弹窗状态
				showAlipayModal: false,
				showCashTypeModal: false,
				showCashAmountModal: false,
				showPayPasswordModal: false,

				// 表单数据
				alipayAccount: '',
				cashAmount: '',
				payPassword: '',

				// 支付密码相关
				payPasswordTitle: '检验支付密码',
				isSettingPassword: false,
				firstPassword: '',
				secondPassword: '',

				// 提现类型
				withdrawType: '' // 'alipay' 或 'bankcard'
			}
		},

		onLoad() {
			this.loadWalletInfo()
		},

		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 账单页面
			goBill() {
				uni.navigateTo({
					url: '/pages/my/zhangdan'
				})
			},

			// 加载钱包信息
			async loadWalletInfo() {
				try {
					const res = await walletApi.getUserAccount()
					if (res.r === 0) {
						this.walletInfo = res.data
					}
				} catch (error) {
					console.error('加载钱包信息失败:', error)
				}
			},

			// 处理提现操作
			async handleWithdraw() {
				try {
					// 检查身份认证
					await this.checkIdentity()
					// 显示提现方式选择
					this.showCashTypeModal = true
				} catch (error) {
					console.error('身份验证失败:', error)
				}
			},

			// 检查身份认证
			async checkIdentity() {
				try {
					const res = await identityApi.getIdentityInfo()
					if (res.r !== 0 || !res.data.is_checked) {
						uni.showToast({
							title: '请先完成身份认证',
							icon: 'none'
						})
						throw new Error('身份未认证')
					}
				} catch (error) {
					throw error
				}
			},

			// 银行卡
			async goBankCard() {
				try {
					await this.checkIdentity()
					uni.navigateTo({
						url: '/pages/my/bankcard'
					})
				} catch (error) {
					console.error('跳转银行卡页面失败:', error)
				}
			},

			// 常见问题
			goFAQ() {
				uni.navigateTo({
					url: '/pages/help/question'
				})
			},

			// 选择银行卡提现
			async selectBankCard() {
				this.hideCashTypeModal()
				try {
					const res = await walletApi.getBankCardList()
					if (res.r === 0) {
						if (!res.data.list || res.data.list.length === 0) {
							uni.showToast({
								title: '你还没有绑定银行卡!',
								icon: 'none'
							})
							return
						}
						// 跳转到银行卡提现页面
						uni.setStorageSync('mycardInfor', res.data)
						uni.navigateTo({
							url: '/pages/my/cash_withdrawal'
						})
					}
				} catch (error) {
					console.error('获取银行卡列表失败:', error)
				}
			},

			// 选择支付宝提现
			selectAlipay() {
				this.hideCashTypeModal()
				this.withdrawType = 'alipay'
				this.showPayPasswordCheck()
			},

			// 显示支付密码验证
			async showPayPasswordCheck() {
				try {
					const res = await walletApi.checkPayPassword()
					if (res.r === 0) {
						this.isSettingPassword = res.data.is_set === 0
						this.payPasswordTitle = this.isSettingPassword ? '设置支付密码' : '请输入支付密码'
						this.showPayPasswordModal = true
					}
				} catch (error) {
					console.error('检查支付密码失败:', error)
				}
			},

			// 处理密码输入
			async handlePasswordInput() {
				if (this.payPassword.length < 6) return

				// 验证是否为纯数字
				if (!/^[0-9]*$/.test(this.payPassword)) {
					uni.showToast({
						title: '支付密码由六位数字组成',
						icon: 'none'
					})
					this.payPassword = ''
					return
				}

				if (this.isSettingPassword) {
					await this.handleSetPassword()
				} else {
					await this.handleVerifyPassword()
				}
			},

			// 处理设置密码
			async handleSetPassword() {
				if (!this.firstPassword) {
					this.firstPassword = this.payPassword
					this.payPassword = ''
					this.payPasswordTitle = '请再次输入支付密码'
				} else if (!this.secondPassword) {
					this.secondPassword = this.payPassword
					if (this.secondPassword !== this.firstPassword) {
						uni.showToast({
							title: '两次密码输入不一致',
							icon: 'none'
						})
						this.secondPassword = ''
						this.payPassword = ''
						return
					}

					try {
						const res = await walletApi.setPayPassword({
							pay_pwd: md5(this.firstPassword),
							pay_confirm_pwd: md5(this.secondPassword)
						})

						if (res.r === 0) {
							uni.showToast({
								title: '支付密码设置成功',
								icon: 'success'
							})
							this.isSettingPassword = false
							this.payPasswordTitle = '请输入支付密码'
							this.resetPasswordData()
						} else {
							uni.showToast({
								title: res.msg || '设置失败',
								icon: 'none'
							})
						}
					} catch (error) {
						console.error('设置支付密码失败:', error)
					}
				}
			},

			// 处理验证密码
			async handleVerifyPassword() {
				try {
					const res = await walletApi.verifyPayPassword({
						pay_pwd: md5(this.payPassword)
					})

					if (res.r === 0) {
						this.hidePayPasswordModal()
						this.showAlipayModal = true
					} else {
						uni.showToast({
							title: res.msg || '密码错误',
							icon: 'none'
						})
						this.payPassword = ''
					}
				} catch (error) {
					console.error('验证支付密码失败:', error)
					this.payPassword = ''
				}
			},

			// 确认支付宝账号
			confirmAlipayAccount() {
				const emailReg =
					/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i
				const phoneReg = /^1[3-9]\d{9}$/

				if (!this.alipayAccount.trim()) {
					uni.showToast({
						title: '支付宝账号必填!',
						icon: 'none'
					})
					return
				}

				if (!emailReg.test(this.alipayAccount) && !phoneReg.test(this.alipayAccount)) {
					uni.showToast({
						title: '请输入正确的支付宝账号!',
						icon: 'none'
					})
					return
				}

				this.hideAlipayModal()
				this.showCashAmountModal = true
			},

			// 提交提现金额
			async submitCashAmount() {
				if (!this.cashAmount.trim()) {
					uni.showToast({
						title: '请输入提现金额',
						icon: 'none'
					})
					return
				}

				try {
					const res = await walletApi.alipayWithdraw({
						money: this.cashAmount,
						alipayAccount: this.alipayAccount
					})

					uni.showToast({
						title: res.msg || '提现申请已提交',
						icon: res.r === 0 ? 'success' : 'none'
					})

					this.hideCashAmountModal()
					this.resetFormData()

					if (res.r === 0) {
						this.loadWalletInfo() // 刷新钱包信息
					}
				} catch (error) {
					console.error('提现失败:', error)
				}
			},

			// 隐藏弹窗方法
			hideAlipayModal() {
				this.showAlipayModal = false
			},

			hideCashTypeModal() {
				this.showCashTypeModal = false
			},

			hideCashAmountModal() {
				this.showCashAmountModal = false
				this.resetFormData()
			},

			hidePayPasswordModal() {
				this.showPayPasswordModal = false
				this.resetPasswordData()
			},

			// 重置表单数据
			resetFormData() {
				this.alipayAccount = ''
				this.cashAmount = ''
				this.withdrawType = ''
			},

			// 重置密码数据
			resetPasswordData() {
				this.payPassword = ''
				this.firstPassword = ''
				this.secondPassword = ''
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wallet-page {
		background-color: #eeeeee;
		min-height: 100vh;
		color: #4d4d4d;
	}

	// 顶部导航栏
	.header-bar {
		height: 88rpx;
		background-color: #ff5722;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		position: relative;

		.back-btn {
			width: 40rpx;
			height: 40rpx;
		}

		.page-title {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			font-size: 36rpx;
			color: #fff;
			font-weight: 500;
		}

		.bill-link {
			font-size: 28rpx;
			color: #fff;
		}
	}

	// 钱包背景卡片
	.wallet-bg {
		height: 450rpx;
		width: 100%;
		color: #fff;
		text-align: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;

		.wallet-bg-image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
		}

		.balance-amount {
			font-size: 36rpx;
			margin-bottom: 20rpx;
			position: relative;
			z-index: 2;
		}

		.balance-label {
			font-size: 30rpx;
			position: relative;
			z-index: 2;
		}
	}

	// 功能列表
	.function-list {
		width: 100%;
		background: #fff;
		border-top: 1rpx solid #e2e2e2;


	}

	.function-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		// padding-left: 154rpx;
		padding-right: 40rpx;
		background-color: white;
		padding-top: 30rpx;
		padding-bottom: 30rpx;
		border-bottom: 1rpx solid #e2e2e2;
		position: relative;

		&.margin-top {
			margin-top: 30rpx;
		}

		.item-left {
			display: flex;
			align-items: center;

			.item-icon {
				// position: absolute;
				// left: 40rpx;
				margin-left: 40rpx;

				width: 52rpx;
				height: 44rpx;
			}

			.item-title {
				font-size: 26rpx;
				margin-left: 30rpx;
				color: #4d4d4d;
			}
		}

		.item-right {
			display: flex;
			align-items: center;

			.frozen-money,
			.withdraw-money {
				font-size: 26rpx;
				color: #4d4d4d;
				margin-right: 20rpx;
			}

			.arrow-right {
				width: 14rpx;
				height: 24rpx;
			}
		}
	}

	// 底部提示
	.bottom-tip {
		position: absolute;
		bottom: 100rpx;
		left: 0;
		right: 0;
		text-align: center;

		.tip-text {
			font-size: 20rpx;
			color: #8d8d8d;
			display: inline;
		}

		.tip-link {
			font-size: 20rpx;
			color: #ff2e00;
			display: inline;
			margin-left: 20rpx;
		}
	}

	// 弹窗遮罩
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	// 支付宝账号弹窗
	.alipay-modal {
		width: 560rpx;
		background: #fff;
		border-radius: 20rpx;
		position: relative;
		display: flex;
		flex-direction: column;

		.modal-title {
			width: 100%;
			height: 109rpx;
			text-align: center;
			line-height: 109rpx;
			font-size: 30rpx;
			color: #333;
		}

		.input-wrapper {
			width: 452rpx;
			height: 128rpx;
			margin: 0 auto;
			display: flex;
			align-items: center;

			input {
				width: 100%;
				height: 64rpx;
				line-height: 64rpx;
				padding: 0 20rpx;
				border: 1rpx solid #e5e5e5;
				border-radius: 10rpx;
				font-size: 28rpx;
				box-sizing: border-box;
			}
		}

		.modal-buttons {
			width: 100%;
			height: 91rpx;
			border-top: 1rpx solid #e5e5e5;
			display: flex;

			.btn-cancel,
			.btn-confirm {
				width: 50%;
				text-align: center;
				line-height: 90rpx;
				font-size: 30rpx;
				color: #333;
			}

			.btn-cancel {
				border-right: 1rpx solid #e5e5e5;
			}

			.btn-confirm {
				color: red;
			}
		}
	}

	// 提现方式选择弹窗
	.cash-type-modal {
		background: #fff;
		width: 100%;
		height: 400rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 10;

		.modal-header {
			background-color: #f2f2f2;
			color: #666;
			font-size: 26rpx;
			height: 90rpx;
			line-height: 90rpx;
			text-align: center;
		}

		.modal-desc {
			height: 90rpx;
			line-height: 90rpx;
			text-align: center;
			font-size: 26rpx;
			color: #ff1e00;
		}

		.cash-option {
			height: 92rpx;
			line-height: 90rpx;
			text-align: center;
			border-top: 1rpx solid #ececec;
			border-bottom: 1rpx solid #ececec;
			font-size: 20rpx;
		}
	}

	// 提现金额输入弹窗
	.cash-amount-modal {
		width: 1120rpx;
		height: 820rpx;
		background: #fff;
		border-radius: 40rpx;
		font-size: 60rpx;
		position: relative;

		.modal-title {
			height: 220rpx;
			line-height: 220rpx;
			text-align: center;
			font-size: 64rpx;
		}

		.modal-desc {
			padding: 0 120rpx;
			font-size: 28rpx;
			text-align: center;
			color: #666;
			margin-bottom: 40rpx;
		}

		.amount-input-wrapper {
			width: 904rpx;
			height: 274rpx;
			margin: 0 auto;
			position: relative;

			input {
				padding-left: 40rpx;
				position: absolute;
				top: 0;
				bottom: 0;
				left: 0;
				right: 0;
				margin: auto;
				width: 100%;
				height: 124rpx;
				border: 1rpx solid #e5e5e5;
				border-radius: 20rpx;
				font-size: 28rpx;
			}
		}

		.modal-buttons {
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			display: flex;

			.btn-cancel,
			.btn-confirm {
				border-top: 1rpx solid #e5e5e5;
				width: 50%;
				text-align: center;
				line-height: 180rpx;
				font-size: 32rpx;
			}

			.btn-confirm {
				color: #ff2e00;
			}
		}
	}

	// 支付密码验证弹窗
	.pay-password-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: #fff;
		z-index: 10;

		.modal-header {
			height: 88rpx;
			background-color: #ff5722;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			.back-btn {
				position: absolute;
				left: 30rpx;
				width: 40rpx;
				height: 40rpx;
			}

			.modal-title {
				font-size: 36rpx;
				color: #fff;
			}
		}

		.password-content {
			padding: 60rpx 40rpx;

			.password-tip {
				font-size: 26rpx;
				color: #4d4d4d;
				margin-bottom: 40rpx;
			}

			.password-input-wrapper {
				input {
					width: 100%;
					height: 80rpx;
					border: 1rpx solid #e5e5e5;
					border-radius: 10rpx;
					padding: 0 20rpx;
					font-size: 32rpx;
				}
			}
		}
	}
</style>